#include <fermat/common/timezone.h>
#include <fermat/common/timestamp.h>
#include <fermat/common/mutex.h>
#include <fermat/common/scoped_lock.h>
#include <ctime>


namespace fermat {
class TZInfo
{
public:
	TZInfo()
	{
		tzset();
	}
	
	int timeZone()
	{
		ScopedMutex lock(&_mutex);
		tzset();
		return -timezone;
	}
	
	const char* name(bool dst)
	{
		ScopedMutex lock(&_mutex);
		tzset();		
		return tzname[dst ? 1 : 0];
	}
		
private:
	Mutex _mutex;
};


static TZInfo tzInfo;


int Timezone::utcOffset()
{
	return tzInfo.timeZone();
}

	
int Timezone::dst()
{
	Timestamp timestamp;
	std::time_t now = timestamp.epochTime();
	struct std::tm t;
	localtime_r(&now, &t);		
	return t.tm_isdst == 1 ? 3600 : 0;
}


bool Timezone::isDst(const Timestamp& timestamp)
{
	std::time_t now = timestamp.epochTime();
	struct std::tm t;
	localtime_r(&now, &t);
	return t.tm_isdst > 0;
}

	
std::string Timezone::name()
{
	return std::string(tzInfo.name(dst() != 0));
}

	
std::string Timezone::standardName()
{
	return std::string(tzInfo.name(false));
}

	
std::string Timezone::dstName()
{
	return std::string(tzInfo.name(true));
}



int Timezone::tzd()
{
	return utcOffset() + dst();
}


} 